import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.List;
import java.util.Random;

public class MainFrame extends JFrame {
    private final DataManager dataManager;

    public MainFrame() {
        dataManager = DataManager.getInstance();
        initializeUI();
    }

    private void initializeUI() {
        setTitle("教育管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        JPanel navBar = new JPanel(new BorderLayout());
        navBar.setBackground(Color.WHITE);
        navBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        buttonPanel.setBackground(Color.WHITE);

        JButton classManageBtn = createNavButton("班级管理");
        JButton groupManageBtn = createNavButton("小组管理");
        JButton studentManageBtn = createNavButton("学生管理");
        JButton randomSelectBtn = createNavButton("随机点名");

        buttonPanel.add(classManageBtn);
        buttonPanel.add(groupManageBtn);
        buttonPanel.add(studentManageBtn);
        buttonPanel.add(randomSelectBtn);

        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
        controlPanel.setBackground(Color.WHITE);

        JButton minBtn = createControlButton("—");
        JButton closeBtn = createControlButton("×");

        minBtn.addActionListener(e -> setState(JFrame.ICONIFIED));
        closeBtn.addActionListener(e -> System.exit(0));

        controlPanel.add(minBtn);
        controlPanel.add(closeBtn);

        navBar.add(buttonPanel, BorderLayout.WEST);
        navBar.add(controlPanel, BorderLayout.EAST);

        JPanel contentPanel = new JPanel();
        contentPanel.setBackground(Color.WHITE);

        mainPanel.add(navBar, BorderLayout.NORTH);
        mainPanel.add(contentPanel, BorderLayout.CENTER);

        add(mainPanel);

        addWindowDragListener();
    }

    private JButton createNavButton(String text) {
        JButton button = new JButton(text);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setBackground(Color.WHITE);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        
        button.addActionListener(e -> {
            switch(text) {
                case "班级管理" -> showClassManagement();
                case "小组管理" -> showGroupManagement();
                case "学生管理" -> showStudentManagement();
                case "随机点名" -> showRandomSelection();
            }
        });
        
        return button;
    }

    private JButton createControlButton(String text) {
        JButton button = new JButton(text);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setBackground(Color.WHITE);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        button.setPreferredSize(new Dimension(45, 30));
        
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                button.setBackground(text.equals("×") ? Color.RED : Color.LIGHT_GRAY);
                button.setForeground(Color.WHITE);
            }
            public void mouseExited(MouseEvent e) {
                button.setBackground(Color.WHITE);
                button.setForeground(Color.BLACK);
            }
        });
        
        return button;
    }

    private void addWindowDragListener() {
        Point origin = new Point();
        
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                origin.x = e.getX();
                origin.y = e.getY();
            }
        });
        
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Point p = getLocation();
                setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y);
            }
        });
    }

    private void showClassManagement() {
        JDialog dialog = createDialog("班级管理");
        JPanel panel = new JPanel(new GridLayout(4, 1, 5, 5));

        JButton addBtn = new JButton("新增班级");
        addBtn.addActionListener(e -> {
            String className = JOptionPane.showInputDialog("请输入班级名称：");
            if (className != null && !className.trim().isEmpty()) {
                boolean classExists = dataManager.getClasses().stream()
                        .anyMatch(c -> c.getClassName().equals(className.trim()));
                
                if (classExists) {
                    JOptionPane.showMessageDialog(dialog, 
                        "已存在同名班级！", 
                        "错误", 
                        JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                dataManager.addClass(className.trim());
                JOptionPane.showMessageDialog(dialog, "班级添加成功！");
            }
        });

        JButton maintainBtn = new JButton("维护班级");
        maintainBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择要维护的班级：",
                    "维护班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                String[] options = {"修改名称", "删除班级"};
                int choice = JOptionPane.showOptionDialog(
                        dialog,
                        "请选择操作：",
                        "维护班级",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        options,
                        options[0]);

                if (choice == 0) {
                    String newName = JOptionPane.showInputDialog(
                            dialog,
                            "请输入新的班级名称：",
                            selectedClass);
                    if (newName != null && !newName.trim().isEmpty()) {
                        selectedClassObj.setClassName(newName);
                        JOptionPane.showMessageDialog(dialog, "班级名称修改成功！");
                    }
                } else if (choice == 1) {
                    int confirm = JOptionPane.showConfirmDialog(
                            dialog,
                            "确定要删除班级 " + selectedClass + " 吗？",
                            "确认删除",
                            JOptionPane.YES_NO_OPTION);
                    if (confirm == JOptionPane.YES_OPTION) {
                        dataManager.removeClass(selectedClassObj.getId());
                        JOptionPane.showMessageDialog(dialog, "班级删除成功！");
                    }
                }
            }
        });

        JButton listBtn = new JButton("班级列表");
        listBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("班级列表：\n\n");
            for (Class c : classes) {
                sb.append("ID: ").append(c.getId())
                  .append(", 名称: ").append(c.getClassName())
                  .append("\n");
            }

            JTextArea textArea = new JTextArea(sb.toString());
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(300, 200));

            JOptionPane.showMessageDialog(
                    dialog,
                    scrollPane,
                    "班级列表",
                    JOptionPane.INFORMATION_MESSAGE);
        });

        JButton closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> dialog.dispose());

        panel.add(addBtn);
        panel.add(maintainBtn);
        panel.add(listBtn);
        panel.add(closeBtn);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showGroupManagement() {
        JDialog dialog = createDialog("小组管理");
        JPanel panel = new JPanel(new GridLayout(4, 1, 5, 5));

        JButton addBtn = new JButton("新增小组");
        addBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请先创建班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                String groupName = JOptionPane.showInputDialog("请输入小组名称：");
                if (groupName != null && !groupName.trim().isEmpty()) {
                    Class selectedClassObj = classes.stream()
                            .filter(c -> c.getClassName().equals(selectedClass))
                            .findFirst()
                            .get();

                    boolean groupExists = dataManager.getGroups().stream()
                            .filter(g -> g.getClassId() == selectedClassObj.getId())
                            .anyMatch(g -> g.getGroupName().equals(groupName.trim()));
                    
                    if (groupExists) {
                        JOptionPane.showMessageDialog(dialog, 
                            "该班级中已存在同名小组！", 
                            "错误", 
                            JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    dataManager.addGroup(groupName.trim(), selectedClassObj.getId());
                    JOptionPane.showMessageDialog(dialog, "小组添加成功！");
                }
            }
        });

        JButton maintainBtn = new JButton("维护小组");
        maintainBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                List<Group> classGroups = dataManager.getGroups().stream()
                        .filter(g -> g.getClassId() == selectedClassObj.getId())
                        .toList();

                if (classGroups.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, 
                        "该班级还没有小组！", 
                        "提示", 
                        JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String[] groupNames = classGroups.stream()
                        .map(g -> g.getGroupName())
                        .toArray(String[]::new);
                
                String selectedGroup = (String) JOptionPane.showInputDialog(
                        dialog,
                        "请选择要维护的小组：",
                        "维护小组",
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        groupNames,
                        groupNames[0]);

                if (selectedGroup != null) {
                    Group selectedGroupObj = classGroups.stream()
                            .filter(g -> g.getGroupName().equals(selectedGroup))
                            .findFirst()
                            .get();

                    String[] options = {"修改名称", "删除小组"};
                    int choice = JOptionPane.showOptionDialog(
                            dialog,
                            "请选择操作：",
                            "维护小组",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            options,
                            options[0]);

                    if (choice == 0) {
                        String newName = JOptionPane.showInputDialog(
                                dialog,
                                "请输入新的小组名称：",
                                selectedGroup);
                        if (newName != null && !newName.trim().isEmpty()) {
                            selectedGroupObj.setGroupName(newName);
                            JOptionPane.showMessageDialog(dialog, "小组名称修改成功！");
                        }
                    } else if (choice == 1) {
                        int confirm = JOptionPane.showConfirmDialog(
                                dialog,
                                "确定要删除小组 " + selectedGroup + " 吗？",
                                "确认删除",
                                JOptionPane.YES_NO_OPTION);
                        if (confirm == JOptionPane.YES_OPTION) {
                            dataManager.removeGroup(selectedGroupObj.getId());
                            JOptionPane.showMessageDialog(dialog, "小组删除成功！");
                        }
                    }
                }
            }
        });

        JButton listBtn = new JButton("小组列表");
        listBtn.addActionListener(e -> {
            List<Group> groups = dataManager.getGroups();
            if (groups.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有小组！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("小组列表：\n\n");
            for (Group g : groups) {
                sb.append("ID: ").append(g.getId())
                  .append(", 名称: ").append(g.getGroupName())
                  .append(", 班级ID: ").append(g.getClassId())
                  .append("\n");
            }

            JTextArea textArea = new JTextArea(sb.toString());
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(300, 200));

            JOptionPane.showMessageDialog(
                    dialog,
                    scrollPane,
                    "小组列表",
                    JOptionPane.INFORMATION_MESSAGE);
        });

        JButton closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> dialog.dispose());

        panel.add(addBtn);
        panel.add(maintainBtn);
        panel.add(listBtn);
        panel.add(closeBtn);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showStudentManagement() {
        JDialog dialog = createDialog("学生管理");
        JPanel panel = new JPanel(new GridLayout(4, 1, 5, 5));

        JButton addBtn = new JButton("新增学生");
        addBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请先创建班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                List<Group> classGroups = dataManager.getGroups().stream()
                        .filter(g -> g.getClassId() == selectedClassObj.getId())
                        .toList();

                if (classGroups.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, 
                        "该班级还没有小组，请先创建小组！", 
                        "提示", 
                        JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String[] groupNames = classGroups.stream()
                        .map(g -> g.getGroupName())
                        .toArray(String[]::new);

                String selectedGroup = (String) JOptionPane.showInputDialog(
                        dialog,
                        "请选择小组：",
                        "选择小组",
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        groupNames,
                        groupNames[0]);

                if (selectedGroup != null) {
                    String studentName = JOptionPane.showInputDialog("请输入学生姓名：");
                    if (studentName != null && !studentName.trim().isEmpty()) {
                        Group selectedGroupObj = classGroups.stream()
                                .filter(g -> g.getGroupName().equals(selectedGroup))
                                .findFirst()
                                .get();
                        dataManager.addStudent(studentName, selectedClassObj.getId(), selectedGroupObj.getId());
                        JOptionPane.showMessageDialog(dialog, "学生添加成功！");
                    }
                }
            }
        });

        JButton maintainBtn = new JButton("维护学生");
        maintainBtn.addActionListener(e -> {
            List<Student> students = dataManager.getStudents();
            if (students.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有学生！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] studentNames = students.stream()
                    .map(s -> s.getName())
                    .toArray(String[]::new);
            
            String selectedStudent = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择要维护的学生：",
                    "维护学生",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    studentNames,
                    studentNames[0]);

            if (selectedStudent != null) {
                Student selectedStudentObj = students.stream()
                        .filter(s -> s.getName().equals(selectedStudent))
                        .findFirst()
                        .get();

                String[] options = {"修改姓名", "删除学生"};
                int choice = JOptionPane.showOptionDialog(
                        dialog,
                        "请选择操作：",
                        "维护学生",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        options,
                        options[0]);

                if (choice == 0) {
                    String newName = JOptionPane.showInputDialog(
                            dialog,
                            "请输入新的学生姓名：",
                            selectedStudent);
                    if (newName != null && !newName.trim().isEmpty()) {
                        selectedStudentObj.setName(newName);
                        JOptionPane.showMessageDialog(dialog, "学生姓名修改成功！");
                    }
                } else if (choice == 1) {
                    int confirm = JOptionPane.showConfirmDialog(
                            dialog,
                            "确定要删除学生 " + selectedStudent + " 吗？",
                            "确认删除",
                            JOptionPane.YES_NO_OPTION);
                    if (confirm == JOptionPane.YES_OPTION) {
                        dataManager.removeStudent(selectedStudentObj.getId());
                        JOptionPane.showMessageDialog(dialog, "学生删除成功！");
                    }
                }
            }
        });

        JButton listBtn = new JButton("学生列表");
        listBtn.addActionListener(e -> showStudentList(dialog));

        JButton closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> dialog.dispose());

        panel.add(addBtn);
        panel.add(maintainBtn);
        panel.add(listBtn);
        panel.add(closeBtn);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showRandomSelection() {
        JDialog dialog = createDialog("随机点名");
        JPanel panel = new JPanel(new GridLayout(5, 1, 5, 5));

        JButton randomGroupBtn = new JButton("随机抽取小组");
        randomGroupBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                // 获取该班级的所有小组
                List<Group> classGroups = dataManager.getGroups().stream()
                        .filter(g -> g.getClassId() == selectedClassObj.getId())
                        .toList();

                if (classGroups.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, 
                        "该班级还没有小组！", 
                        "提示", 
                        JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 随机选择一个小组
                Random random = new Random();
                Group randomGroup = classGroups.get(random.nextInt(classGroups.size()));

                JOptionPane.showMessageDialog(dialog, 
                    String.format("班级：%s\n小组：%s", 
                        selectedClass, 
                        randomGroup.getGroupName()));
            }
        });

        JButton randomStudentFromGroupBtn = new JButton("随机在小组中抽取学生");
        randomStudentFromGroupBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                List<Group> classGroups = dataManager.getGroups().stream()
                        .filter(g -> g.getClassId() == selectedClassObj.getId())
                        .toList();

                if (classGroups.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, 
                        "该班级还没有小组！", 
                        "提示", 
                        JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String[] groupNames = classGroups.stream()
                        .map(g -> g.getGroupName())
                        .toArray(String[]::new);

                String selectedGroup = (String) JOptionPane.showInputDialog(
                        dialog,
                        "请选择小组：",
                        "选择小组",
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        groupNames,
                        groupNames[0]);

                if (selectedGroup != null) {
                    Group selectedGroupObj = classGroups.stream()
                            .filter(g -> g.getGroupName().equals(selectedGroup))
                            .findFirst()
                            .get();
                    
                    Student student = dataManager.getRandomStudentFromGroup(selectedGroupObj.getId());
                    if (student != null) {
                        JOptionPane.showMessageDialog(dialog, 
                            "抽中的学生是：" + student.getName());
                    } else {
                        JOptionPane.showMessageDialog(dialog, 
                            "该小组中没有学生！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });

        JButton randomStudentFromClassBtn = new JButton("随机在班级里抽取学生");
        randomStudentFromClassBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();
                
                Student student = dataManager.getRandomStudentFromClass(selectedClassObj.getId());
                if (student != null) {
                    JOptionPane.showMessageDialog(dialog, 
                        "抽中的学生是：" + student.getName());
                } else {
                    JOptionPane.showMessageDialog(dialog, 
                        "该班级中没有学生！", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        JButton recordBtn = new JButton("记录学生考勤/答题情况");
        recordBtn.addActionListener(e -> {
            List<Class> classes = dataManager.getClasses();
            if (classes.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "当前没有班级！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String[] classNames = classes.stream()
                    .map(c -> c.getClassName())
                    .toArray(String[]::new);
            
            String selectedClass = (String) JOptionPane.showInputDialog(
                    dialog,
                    "请选择班级：",
                    "选择班级",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    classNames,
                    classNames[0]);

            if (selectedClass != null) {
                Class selectedClassObj = classes.stream()
                        .filter(c -> c.getClassName().equals(selectedClass))
                        .findFirst()
                        .get();

                List<Student> classStudents = dataManager.getStudents().stream()
                        .filter(s -> s.getClassId() == selectedClassObj.getId())
                        .toList();

                if (classStudents.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "该班级还没有学生！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String[] studentNames = classStudents.stream()
                        .map(s -> s.getName())
                        .toArray(String[]::new);
                
                String selectedStudent = (String) JOptionPane.showInputDialog(
                        dialog,
                        "请选择学生：",
                        "选择学生",
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        studentNames,
                        studentNames[0]);

                if (selectedStudent != null) {
                    Student selectedStudentObj = classStudents.stream()
                            .filter(s -> s.getName().equals(selectedStudent))
                            .findFirst()
                            .get();

                    String[] options = {"记录考勤", "记录答题"};
                    int choice = JOptionPane.showOptionDialog(
                            dialog,
                            "请选择记录类型：",
                            "记录类型",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            options,
                            options[0]);

                    if (choice == 0) { // 记录考勤
                        String[] attendanceOptions = {"出勤", "缺勤", "迟到"};
                        String attendance = (String) JOptionPane.showInputDialog(
                                dialog,
                                "请选择考勤状态：",
                                "考勤记录",
                                JOptionPane.QUESTION_MESSAGE,
                                null,
                                attendanceOptions,
                                attendanceOptions[0]);
                        
                        if (attendance != null) {
                            int status = switch (attendance) {
                                case "出勤" -> 1;
                                case "缺勤" -> 0;
                                case "迟到" -> 2;
                                default -> 0;
                            };
                            dataManager.recordAttendance(selectedStudentObj.getId(), status);
                            JOptionPane.showMessageDialog(dialog, "考勤记录成功！");
                        }
                    } else if (choice == 1) { // 记录答题
                        String scoreStr = JOptionPane.showInputDialog(
                                dialog,
                                "请输入答题得分（0-100）：",
                                "0");
                        
                        if (scoreStr != null) {
                            try {
                                int score = Integer.parseInt(scoreStr);
                                if (score >= 0 && score <= 100) {
                                    dataManager.recordScore(selectedStudentObj.getId(), score);
                                    JOptionPane.showMessageDialog(dialog, "答题记录成功！");
                                } else {
                                    JOptionPane.showMessageDialog(dialog, 
                                        "分数必须在0-100之间！", 
                                        "错误", 
                                        JOptionPane.ERROR_MESSAGE);
                                }
                            } catch (NumberFormatException ex) {
                                JOptionPane.showMessageDialog(dialog, 
                                    "请输入有效的数字！", 
                                    "错误", 
                                    JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }
                }
            }
        });

        panel.add(randomGroupBtn);
        panel.add(randomStudentFromGroupBtn);
        panel.add(randomStudentFromClassBtn);
        panel.add(recordBtn);

        JButton closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> dialog.dispose());
        panel.add(closeBtn);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        dialog.add(panel);
        dialog.setVisible(true);
    }

    private JDialog createDialog(String title) {
        JDialog dialog = new JDialog(this, title, true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);
        return dialog;
    }

    private void showStudentList(JDialog dialog) {
        List<Student> students = dataManager.getStudents();
        if (students.isEmpty()) {
            JOptionPane.showMessageDialog(dialog, "当前没有学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("学生列表：\n\n");
        
        // 定义每列的宽度
        String format = "%-6s %-8s %-10s %-10s %-10s %-10s %-10s %-10s\n";
        
        // 添加表头
        sb.append(String.format(format,
                "ID", "姓名", "班级ID", "小组ID", "出勤数", "缺勤数", "迟到数", "总分"));
        sb.append("=".repeat(85)).append("\n");
        
        // 添加数据行
        for (Student s : students) {
            sb.append(String.format(format,
                    s.getId(),
                    s.getName(),
                    s.getClassId(),
                    s.getGroupId(),
                    s.getAttendance(),
                    s.getAbsences(),
                    s.getLateCount(),
                    s.getTotalScore()));
        }

        JTextArea textArea = new JTextArea(sb.toString());
        textArea.setEditable(false);
        textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(600, 300));

        JOptionPane.showMessageDialog(
                dialog,
                scrollPane,
                "学生列表",
                JOptionPane.INFORMATION_MESSAGE);
    }
} 